/******************************************************************************
@file:  SearchResult.java
@author Ramesh Anandhan

DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
******************************************************************************/
package com.smartc.ui;

import java.util.ArrayList;
import java.util.Calendar;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.smartc.connection.HttpConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class SearchResult extends Activity {

	protected static final String TAG = "SearchResult";
	private final int PROGRESS_DLG = 0x01;
	private ArrayList<Object> itemList;
	private ItemBean bean;
	
	private ListView mItemListView;
	private ListViewAdapter adapter;
	//private View mResult_view;
	
	private String mSelectedRoute;
	private String mSearchType;
	
	private String mBLocationId;
	private String mEndLocation;
	private String mTime;
	
	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_result);
		Intent intent = getIntent();
		mSearchType = intent.getStringExtra("typeofSearch");
		if(Integer.parseInt(mSearchType) == Search.SEARCH_ROUTE){
			mSelectedRoute = intent.getStringExtra("idRoute");
			Log.i(TAG,"onCreate() mSelectedRoute:"+mSelectedRoute);
		}
		else if(Integer.parseInt(mSearchType) == Search.SEARCH_TIME){
			mBLocationId = intent.getStringExtra("idBoardingLocationId");
			mTime = intent.getStringExtra("tsTime");
			Log.i(TAG,"onCreate() mBLocationId:"+mBLocationId);
			Log.i(TAG,"onCreate() mTime:"+mTime);
		}else{
			mBLocationId = intent.getStringExtra("idBoardingLocationId");
			mEndLocation = intent.getStringExtra("idEndLocationId");
		}
			
		Log.i(TAG,"onCreate() mSearchType:"+mSearchType);
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		switch (id) {
		case PROGRESS_DLG:
			ProgressDialog mDialog = new ProgressDialog(this);
			mDialog.setMessage("Request In progress....");
			mDialog.setIndeterminate(true);
			mDialog.setCancelable(true);
			return mDialog;
		default:
			return super.onCreateDialog(id, args);
		}
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		String domain = getResources().getString(R.string.domain);
		String query = null;
		query = getResources().getString(R.string.url_transport_search);

		String url = domain+query;
		Log.i(TAG,"onStart url:"+url);
		mCityConnection = new HttpConnection();
		mCityConnection.setUrl(url);
		mCityConnection.clearParam();
		mCityConnection.AddParam("typeofSearch", mSearchType);
		if(Integer.parseInt(mSearchType) == Search.SEARCH_ROUTE){
			mCityConnection.AddParam("idRoute", mSelectedRoute);

		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_TIME){
			mCityConnection.AddParam("idBoardingLocationId", mBLocationId);
			mCityConnection.AddParam("tsTime", mTime);
        	TextView header = (TextView) findViewById(R.id.search_result_header);
        	if(mResponse.mBoardingLocation.size() == 0)                		
        		header.setText("No Result");
        	else
        		header.setText("Search Result");
			//Message myMessage=new Message();
			//myMessage.obj="ROUTE";
			//handler.sendMessageDelayed(myMessage, 2000); 
		}else{
			Log.i(TAG,"onCreate() idBoardingLocationId:"+mBLocationId);
			Log.i(TAG,"onCreate() idEndLocationId:"+mEndLocation);
			mCityConnection.AddParam("idBoardingLocationId", mBLocationId);
			mCityConnection.AddParam("idEndLocationId", mEndLocation);
		}
		mCityConnection.AddHandler(mResponse);
		mCityConnection.Execute();
		
        mResponse.mIdLocation.clear();
        mResponse.mtsUpTrip.clear();
        mResponse.mBoardingLocation.clear();
        mResponse.mnmRoute.clear();
        mResponse.mtsDownTrip.clear();
        mResponse.nmTransportService_list.clear();
        showDialog(PROGRESS_DLG);
	}


	public static class ViewHolder{
        TextView BoardingLocation;
        TextView Time;
        TextView Route;
        TextView dTime;
    }
	
	private class ListViewAdapter extends BaseAdapter{
		
		private LayoutInflater inflater;
		//private Context mContext;
		ArrayList<Object> mItemList;
		ListViewAdapter(Context context,ArrayList<Object> itemList){
			super();
			//mContext = context;
			mItemList = itemList;
			this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		
		@Override
		public int getCount() {
			return mItemList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			ViewHolder holder;
	        if(convertView==null)
	        {
	            holder = new ViewHolder();
	            
	    		if(Integer.parseInt(mSearchType) == Search.SEARCH_ROUTE){
	    			convertView = inflater.inflate(R.layout.search_result_list, null);
		            holder.BoardingLocation = (TextView) convertView.findViewById(R.id.result_blocation);
		            holder.Time = (TextView) convertView.findViewById(R.id.result_time);
	    		}
	    		else if(Integer.parseInt(mSearchType) == Search.SEARCH_TIME){
	    			convertView = inflater.inflate(R.layout.search_result_time, null);
		            holder.BoardingLocation = (TextView) convertView.findViewById(R.id.time_result_blocation);
		            holder.Time = (TextView) convertView.findViewById(R.id.time_result_time);
		            holder.Route = (TextView) convertView.findViewById(R.id.result_route);
	    		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_MORNING ||
	    				Integer.parseInt(mSearchType) == Search.SEARCH_EVENING){
	    			convertView = inflater.inflate(R.layout.search_result_session1, null);
		            //holder.BoardingLocation = (TextView) convertView.findViewById(R.id.session_result_route);
		            holder.Time = (TextView) convertView.findViewById(R.id.session_result_uptime_me);
		            holder.Route = (TextView) convertView.findViewById(R.id.session_result_route_me);
	    		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_LMS_MMTS){
	    			convertView = inflater.inflate(R.layout.search_result_session, null);
		            //holder.BoardingLocation = (TextView) convertView.findViewById(R.id.session_result_route);
		            holder.Time = (TextView) convertView.findViewById(R.id.session_result_uptime);
		            holder.Route = (TextView) convertView.findViewById(R.id.session_result_route);
		            holder.dTime = (TextView) convertView.findViewById(R.id.session_result_downtime);
	    		}
	            convertView.setTag(holder);
	        }
	        else
	            holder=(ViewHolder)convertView.getTag();
	        
	        ItemBean bean = (ItemBean) itemList.get(position);
	        if(!(Integer.parseInt(mSearchType) == Search.SEARCH_MORNING ||
    				Integer.parseInt(mSearchType) == Search.SEARCH_EVENING ||
    				Integer.parseInt(mSearchType) == Search.SEARCH_LMS_MMTS)){
	        	holder.BoardingLocation.setText(bean.getBoardingLocation());
	        	        }
	        
	        	holder.Time.setText(bean.getTime());
	        
    		if(Integer.parseInt(mSearchType) == Search.SEARCH_TIME){
    			holder.Route.setText(bean.getRoute());
    		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_MORNING){
    			//holder.dTime.setVisibility(View.INVISIBLE);
    			holder.Route.setText(bean.getRoute());
    		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_EVENING){
    			//holder.Time.setVisibility(View.INVISIBLE);
    			TextView service = (TextView) convertView.findViewById(R.id.session_text_uptime_me);
    			service.setText("Dropping Time: ");
    			//holder.dTime.setText(bean.getDTime());
    			holder.Route.setText(bean.getRoute());
    		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_LMS_MMTS){
    			holder.Route.setText(bean.getRoute());
    			TextView service = (TextView) convertView.findViewById(R.id.session_text_route);
    			service.setText("Service: ");
    			holder.dTime.setText(bean.getDTime());
    		}

	        return convertView;
		}
	}
	

	public class ItemBean
	{
	    String mBoardingLocation;
	    String mTime;
	    String mRoute;
	    String mDTime;
	    
	    public String getBoardingLocation() {
	        return mBoardingLocation;
	    }
	    public void setBoardingLocation(String location) {
	        this.mBoardingLocation = location;
	    }
	    public String getTime() {
	    	return mTime;
	    }
	    public void setTime(String time) {
	        this.mTime = time;
	    }
	    public String getRoute() {
	    	return mRoute;
	    }
	    public void setRoute(String time) {
	        this.mRoute = time;
	    }
	    public String getDTime() {
	    	return mDTime;
	    }
	    public void setDTime(String time) {
	        this.mDTime = time;
	    }
	}
	
   public void AddObjectToList(String location, String time,String route, String dtime){
        bean = new ItemBean();
        bean.setBoardingLocation(location);
        bean.setTime(time);
        bean.setRoute(route);
        bean.setDTime(dtime);
        itemList.add(bean);
    }
	   
	public class ResponseHandler extends DefaultHandler {
		
		//private boolean Routes = false;
		//private boolean Route = false;
		private boolean idLocation = false;
		private boolean tsUpTrip = false;
		private boolean nmBoardingLocation = false;
		private boolean nmRoute = false;
		private boolean tsDownTrip = false;
		private boolean nmTransportService = false;
		
		public ArrayList<String> mBoardingLocation = new ArrayList<String>();
		public ArrayList<String> mIdLocation = new ArrayList<String>();
		public ArrayList<String> mtsUpTrip = new ArrayList<String>();
		public ArrayList<String> mnmRoute = new ArrayList<String>();
		public ArrayList<String> mtsDownTrip = new ArrayList<String>();
		public ArrayList<String> nmTransportService_list = new ArrayList<String>();
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			  if (this.idLocation) {
				  mIdLocation.add(new String(ch, start,length));
			  }else if (this.tsUpTrip) {
				  mtsUpTrip.add(new String(ch, start,length));
			  }	else if (this.nmBoardingLocation) {
				  mBoardingLocation.add(new String(ch, start,length));
			  }else if (this.nmRoute) {
				  mnmRoute.add(new String(ch, start,length));
			  }else if (this.tsDownTrip) {
				  mtsDownTrip.add(new String(ch, start,length));
			  }else if (this.nmTransportService) {
				  nmTransportService_list.add(new String(ch, start,length));
			  }		
		}
		
		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			  if (localName.equals("Routes")) {
					//this.Routes = false;
					Message myMessage=new Message();
					myMessage.obj="SEARCH";
					handler.sendMessage(myMessage); 
			  }else if(localName.equals("Route")){
				  //this.Route = false;
			  }else if(localName.equals("idLocation")){
				  this.idLocation = false;
			  }else if(localName.equals("tsUpTrip")){
				  this.tsUpTrip = false;
			  }else if(localName.equals("nmBoardingLocation")){
				  this.nmBoardingLocation = false;
			  }else if(localName.equals("nmRoute")){
				  this.nmRoute = false;
			  }else if(localName.equals("tsDownTrip")){
				  this.tsDownTrip = false;
			  }else if(localName.equals("nmTransportService")){
				  this.nmTransportService = false;
			  }		
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {			
			  if (localName.equals("Routes")) {
			        //this.Routes = true;
			        mIdLocation.clear();
			        mtsUpTrip.clear();
			        mBoardingLocation.clear();
			        mnmRoute.clear();
			        mtsDownTrip.clear();
			        nmTransportService_list.clear();
			  }else if(localName.equals("Route")){
				  //this.Route = true;
			  }else if(localName.equals("idLocation")){
				  this.idLocation = true;
			  }else if(localName.equals("tsUpTrip")){
				  this.tsUpTrip = true;
			  }else if(localName.equals("nmBoardingLocation")){
				  this.nmBoardingLocation = true;
			  }else if(localName.equals("nmRoute")){
				  this.nmRoute = true;
			  }else if(localName.equals("tsDownTrip")){
				  this.tsDownTrip = true;
			  }else if(localName.equals("nmTransportService")){
				  this.nmTransportService = true;
			  }
		}
	}
		
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage msg:"+(String)msg.obj);
            String loginmsg=(String)msg.obj;
            if(loginmsg!= null && loginmsg.equals("SEARCH")) {
            	removeDialog(PROGRESS_DLG);
            	itemList = new ArrayList<Object>();
            	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage mBoardingLocation size:"+mResponse.mBoardingLocation.size());        	
            	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage mtsUpTrip size:"+mResponse.mtsUpTrip.size());
            	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage mnmRoute size:"+mResponse.mnmRoute.size());
            	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage mtsDownTrip size:"+mResponse.mtsDownTrip.size());
            	if(AccountLogin.DEBUG) Log.i(TAG,"handleMessage nmTransportService_list size:"+mResponse.nmTransportService_list.size());
            	
            	TextView header = (TextView) findViewById(R.id.search_result_header);
            	if(mResponse.mBoardingLocation.size() == 0)                		
            		header.setText("No Result");
            	else
            		header.setText("Search Result");
            	
            	
        		if(Integer.parseInt(mSearchType) == Search.SEARCH_ROUTE){
                	Log.i(TAG,"handleMessage size:"+mResponse.mBoardingLocation.size());
                		
                	for(int i=0;i<mResponse.mBoardingLocation.size();i++){
                		AddObjectToList(mResponse.mBoardingLocation.get(i), mResponse.mtsUpTrip.get(i),null,null);
                	}
        		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_TIME){
                	Log.i(TAG,"handleMessage size:"+mResponse.mBoardingLocation.size());
                	
                	for(int i=0;i<mResponse.mBoardingLocation.size();i++){
                		AddObjectToList(mResponse.mBoardingLocation.get(i), mResponse.mtsUpTrip.get(i),
                					mResponse.mBoardingLocation.get(i),null);
                	}
        		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_MORNING){
        			
                	for(int i=0;i<mResponse.mBoardingLocation.size();i++){
                		AddObjectToList(mResponse.mBoardingLocation.get(i), mResponse.mtsUpTrip.get(i),
                					mResponse.mnmRoute.get(i),mResponse.mtsDownTrip.get(i));
                	}
        		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_EVENING){
        			              	
                	for(int i=0;i<mResponse.mBoardingLocation.size();i++){
                		AddObjectToList(null, mResponse.mtsDownTrip.get(i),
                				mResponse.mnmRoute.get(i),null);
                	}
        		}else if(Integer.parseInt(mSearchType) == Search.SEARCH_LMS_MMTS){
        			      			
                	for(int i=0;i<mResponse.mBoardingLocation.size();i++){
                		AddObjectToList(mResponse.mBoardingLocation.get(i), mResponse.mtsUpTrip.get(i),
                					mResponse.nmTransportService_list.get(i),mResponse.mtsDownTrip.get(i));
                	}
        		}
            	
        		mItemListView = (ListView) findViewById(R.id.search_result);
        		adapter = new ListViewAdapter(SearchResult.this.getApplicationContext(), itemList);
        		mItemListView.setAdapter(adapter);
        		//mItemListView.setOnItemClickListener(SearchResult.this);
            }else if(loginmsg!= null && loginmsg.equals("ROUTE")){
            	TextView header = (TextView) findViewById(R.id.search_result_header);
            	if(mResponse.mBoardingLocation.size() == 0)                		
            		header.setText("No Result");
            	else
            		header.setText("Search Result");
            }
           
        }
    };
}
